package com.zhgxi.zf.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slave4j.orm.Filtration;
import org.slave4j.orm.Filtration.MatchType;
import org.slave4j.orm.hibernate.BaseDao;
import org.slave4j.orm.hibernate.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhgxi.zf.entity.Menu;
import com.zhgxi.zf.entity.Role;
import com.zhgxi.zf.entity.RoleMenu;

@Service
@Transactional
public class RoleMenuService extends BaseService<RoleMenu> {
	@Override
	@Resource(name = "roleMenuDao")
	public void setBaseDao(BaseDao<RoleMenu> baseDao) {
		this.baseDao = baseDao;
	}

	public List<Menu> findMenuByRole(Role role) {
		List<Menu> menuList = new ArrayList<Menu>();
		Filtration visible = new Filtration(MatchType.EQ, true, "visible");
		Filtration r = new Filtration(MatchType.EQ, role, "role");
		List<RoleMenu> rolemenuList = baseDao.findList(visible, r);
		for (RoleMenu rolemenu : rolemenuList) {
			if (rolemenu.getMenu().isVisible()) {
				menuList.add(rolemenu.getMenu());
			}
		}
		return menuList;
	}

	public boolean addRoleMenu(List<Menu> listMenu, Role role) {
		try {
			Filtration roleFilter = new Filtration(MatchType.EQ, role, "role");
			List<RoleMenu> rolemenuList = baseDao.findList(roleFilter);
			for (RoleMenu rolemenu : rolemenuList) {
				baseDao.delete(rolemenu);
			}
			for (Menu m : listMenu) {
				RoleMenu rm = new RoleMenu();
				rm.setMenu(m);
				rm.setRole(role);
				baseDao.save(rm);
			}
			return true;
		} catch (Exception e) {
			return false;
		}

	}
}
